package top.zywork.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.zywork.annotation.SysLog;
import top.zywork.common.BeanUtils;
import top.zywork.common.BindingResultUtils;
import top.zywork.common.StringUtils;
import top.zywork.dto.GoodsOrderDTO;
import top.zywork.dto.PagerDTO;
import top.zywork.enums.GoodsOrderStatusEnum;
import top.zywork.query.GoodsOrderQuery;
import top.zywork.service.GoodsOrderItemService;
import top.zywork.service.GoodsOrderService;
import top.zywork.vo.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * GoodsOrderController控制器类<br/>
 *
 * 创建于2019-07-04<br/>
 *
 * @author http://zywork.top 王振宇
 * @version 1.0
 */
@RestController
@RequestMapping("/goods-order")
@Slf4j
public class GoodsOrderController extends BaseController {

    private GoodsOrderService goodsOrderService;

    private GoodsOrderItemService goodsOrderItemService;

    @PostMapping("admin/save")
    @SysLog(description = "后台保存GoodsOrderVO")
    public ResponseStatusVO save(@RequestBody @Validated GoodsOrderVO goodsOrderVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        goodsOrderService.save(BeanUtils.copy(goodsOrderVO, GoodsOrderDTO.class));
        return ResponseStatusVO.ok("添加成功", null);
    }

    /**
     * 用户保存订单(多个)，同时保存订单项
     * @param agentRole
     * @param goodsOrderAndItemInVOList
     * @param bindingResult
     * @return
     */
    @PostMapping("user/save/{agentRole}")
    @SysLog(description = "用户保存商城订单")
    public ResponseStatusVO userSave(@PathVariable("agentRole") String agentRole, @RequestBody @Validated List<GoodsOrderAndItemInVO> goodsOrderAndItemInVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        Map<Long, String> saveRowsMap = goodsOrderService.saveOrders(agentRole, goodsOrderAndItemInVOList);
        boolean allSkuStockEnough = true;
        for (Map.Entry<Long, String> entry : saveRowsMap.entrySet()) {
            if (entry.getKey() != 0 && Integer.parseInt(entry.getValue()) == 0) {
                allSkuStockEnough = false;
                break;
            }
        }
        return allSkuStockEnough ? ResponseStatusVO.ok("添加成功", saveRowsMap) : ResponseStatusVO.dataError("部分商品库存不足", saveRowsMap);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存GoodsOrderVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<GoodsOrderVO> goodsOrderVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        goodsOrderService.saveBatch(BeanUtils.copyListObj(goodsOrderVOList, GoodsOrderDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    /**
     * 用户删除订单
     * @param id
     * @return
     */
    @GetMapping("user/remove/{id}")
    @SysLog(description = "用户删除商城订单")
    public ResponseStatusVO userRemoveById(@PathVariable("id") Long id) {
        return removeById(id);
    }

    /**
     * 删除订单，包括订单项
     * @param id
     * @return
     */
    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除GoodsOrderVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        Object obj = goodsOrderService.getById(id);
        if (null == obj) {
            return ResponseStatusVO.error("删除失败，订单不存在", null);
        }
        GoodsOrderDTO goodsOrderDTO = BeanUtils.copy(obj, GoodsOrderDTO.class);
        if (goodsOrderDTO.getOrderStatus().intValue() !=  GoodsOrderStatusEnum.CANCELED.getValue()) {
            return ResponseStatusVO.error("删除失败，只有已取消的订单才能删除", null);
        }
        // 删除订单项
        goodsOrderItemService.removeByOrderId(id);
        goodsOrderService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除GoodsOrderVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        goodsOrderService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    /**
     * 用户取消订单
     * @param userGoodsOrderExVO
     * @return
     */
    @PostMapping("user/cancel")
    @SysLog(description = "用户取消商城订单")
    public ResponseStatusVO userCancel(@RequestBody UserGoodsOrderExVO userGoodsOrderExVO) {
        int updateRows = goodsOrderService.cancelOrder(userGoodsOrderExVO);
        return updateRows == 1 ? ResponseStatusVO.ok("已取消订单", null) : ResponseStatusVO.error("订单取消失败，请稍候再试", null);
    }

    /**
     * 用户确认收货
     * @param goodsOrderVO
     * @return
     */
    @PostMapping("user/confirm")
    @SysLog(description = "用户商城订单确认收货")
    public ResponseStatusVO userConfirm(@RequestBody GoodsOrderVO goodsOrderVO) {
        int updateRows = goodsOrderService.confirmOrder(BeanUtils.copy(goodsOrderVO, GoodsOrderDTO.class));
        return updateRows == 1 ? ResponseStatusVO.ok("已确认收货", null) : ResponseStatusVO.error("确认收货失败，请稍候再试", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新GoodsOrderVO")
    public ResponseStatusVO update(@RequestBody @Validated GoodsOrderVO goodsOrderVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        return updateGoodsOrder(goodsOrderVO);
    }

    /**
     * 更新商品订单信息
     * @param goodsOrderVO
     * @return
     */
    public ResponseStatusVO updateGoodsOrder(GoodsOrderVO goodsOrderVO) {
        int updateRows = goodsOrderService.update(BeanUtils.copy(goodsOrderVO, GoodsOrderDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新GoodsOrderVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<GoodsOrderVO> goodsOrderVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        goodsOrderService.updateBatch(BeanUtils.copyListObj(goodsOrderVOList, GoodsOrderDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结GoodsOrderVO")
    public ResponseStatusVO active(@RequestBody GoodsOrderVO goodsOrderVO) {
        goodsOrderService.update(BeanUtils.copy(goodsOrderVO, GoodsOrderDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结GoodsOrderVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<GoodsOrderVO> goodsOrderVOList) {
        goodsOrderService.updateBatch(BeanUtils.copyListObj(goodsOrderVOList, GoodsOrderDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
        Object obj = goodsOrderService.getById(id);
        if (obj != null) {
            goodsOrderVO = BeanUtils.copy(obj, GoodsOrderVO.class);
        }
        return ResponseStatusVO.ok("查询成功", goodsOrderVO);
    }

    @GetMapping("admin/order-no/{orderNo}")
    public ResponseStatusVO getByOrderNo(@PathVariable("orderNo") String orderNo) {
        PagerDTO pagerDTO = PagerDTO.builder().total(0L).rows(new ArrayList<>()).build();
        GoodsOrderDTO goodsOrderDTO = goodsOrderService.getByOrderNo(orderNo);
        if (goodsOrderDTO != null) {
            pagerDTO.setTotal(1L);
            pagerDTO.getRows().add(goodsOrderDTO);
        }
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsOrderVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = goodsOrderService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsOrderVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody GoodsOrderQuery goodsOrderQuery) {
        PagerDTO pagerDTO = goodsOrderService.listAllByCondition(goodsOrderQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsOrderVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody GoodsOrderQuery goodsOrderQuery) {
        PagerDTO pagerDTO = goodsOrderService.listPageByCondition(goodsOrderQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GoodsOrderVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 管理员后台发货
     * @param id
     * @return
     */
    @PostMapping("admin/delivery/{id}")
    @SysLog(description = "后台商城订单发货")
    public ResponseStatusVO deliveryGoods(@PathVariable("id") Long id, @RequestBody GoodsOrderLogisticsVO goodsOrderLogisticsVO) {
        return goodsOrderService.goodsOrderDelivery(id, goodsOrderLogisticsVO);
    }

    @GetMapping("admin/verification/{id}")
    @SysLog(description = "后台商城订单核销")
    public ResponseStatusVO verificationOrder(@PathVariable("id") Long id) {
        return goodsOrderService.goodsOrderVerification(id);
    }

    @GetMapping("user/verification/{id}")
    @SysLog(description = "提货点商城订单核销")
    public ResponseStatusVO userVerificationOrder(@PathVariable("id") Long id) {
        return verificationOrder(id);
    }

    @Autowired
    public void setGoodsOrderService(GoodsOrderService goodsOrderService) {
        this.goodsOrderService = goodsOrderService;
    }

    @Autowired
    public void setGoodsOrderItemService(GoodsOrderItemService goodsOrderItemService) {
        this.goodsOrderItemService = goodsOrderItemService;
    }
}
